<template>
    <el-row>
        <el-col :span="8">
            <div class="grid-content ep-bg-purple"/>
        </el-col>
        <el-col :span="8"
                v-loading="loading"
                element-loading-text="注册中..."
                :element-loading-spinner="loadingSvg"
                element-loading-svg-view-box="-10, -10, 50, 50"
                element-loading-background="rgba(255,250,240,0.8)">
            <div class="grid-content ep-bg-purple-light"/>
            <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="120px"
                    class="demo-ruleForm"
            >
                <el-form-item label="邮箱" prop="username">
                    <el-input v-model="ruleForm.username"/>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" autocomplete="off"/>
                </el-form-item>

                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input v-model="ruleForm.checkPassword" type="password" autocomplete="off"/>
                </el-form-item>

                <el-form-item label="验证码" prop="verificationCode">
                    <el-input style="width: 73%" v-model="ruleForm.verificationCode" type="text" autocomplete="off"/>
                    <el-button style="width: 25%;margin-left: 2%" :disabled="getVerificationCodeBtn.disable"
                               type="primary" @click="getVerificationCode" plain>
                        {{getVerificationCodeBtn.text}}
                    </el-button>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">注册</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="8">
            <div class="grid-content ep-bg-purple"/>
        </el-col>
    </el-row>
</template>


<script lang="ts" setup>
    import {reactive, ref} from 'vue'
    import type {FormInstance} from 'element-plus'
    import {ElMessage} from 'element-plus'
    import {loginFunction, registerFunction} from '@/common/service/login'
    import {sendEmailVerficationCode} from '@/api/email'
    import {useRouter} from 'vue-router'
    import emitter from "@/utils/event-bus"
    import {MittEventEnum} from "@/utils/enum/mitt-event-enum";


    let loading = ref(false)
    // 路由全局配置 相当于vue2中的this.$router
    const router = useRouter()
    const ruleFormRef = ref<FormInstance>()

    // 表单验证相关
    const checkUsername = (rule: any, value: any, callback: any) => {
        if (!value) {
            return callback(new Error('请填写你的邮箱账号！'))
        }
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
        setTimeout(() => {
            if (!regEmail.test(value)) {
                callback(new Error('请输入合法的邮箱!'))
            } else {
                callback()
            }
        }, 1000)
    }

    const validatePass = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error('请填写密码!'))
        } else {
            callback()
        }
    }

    const checkValidatePass = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error('请再次填写密码'))
        } else if (value !== ruleForm.password) {
            callback(new Error("两次填写的密码不一样!"))
        } else {
            callback()
        }
    }

    const checkValidateverificationCode = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error('请输入验证码'))
        } else {
            callback()
        }
    }

    /**
     *可参考重置密码进行优化
     */
        // 验证码相关 start
    let getVerificationCodeBtn = reactive({
            text: "获取验证码",
            disable: false,
            second: 60,
            timer: null
        })

    const getVerificationCode = () => {
        // 调用发送邮件接口
        sendEmailVerficationCode({email: ruleForm.username}).then(res => {
            console.log(res)
        })

        if (getVerificationCodeBtn.timer) {
            clearInterval(getVerificationCodeBtn.timer)// 清除定时器
        }
        getVerificationCodeBtn.timer = setInterval(() => {
            if (getVerificationCodeBtn.second > 0) {
                if (!getVerificationCodeBtn.disable)
                    getVerificationCodeBtn.disable = true
                getVerificationCodeBtn.second--
                getVerificationCodeBtn.text = getVerificationCodeBtn.second + "秒后可重发";
                console.log(getVerificationCodeBtn.second)
            } else {
                clearInterval(getVerificationCodeBtn.timer)
                getVerificationCodeBtn.second = 60
                getVerificationCodeBtn.text = "重发验证码"
                getVerificationCodeBtn.disable = false
            }
        }, 1000)
    }
    // 验证码相关 end

    const ruleForm = reactive({
        username: '',
        password: '',
        checkPassword: '',
        verificationCode: ''
    })

    const rules = reactive({
        username: [{validator: checkUsername, trigger: 'blur'}],
        password: [{validator: validatePass, trigger: 'blur'}],
        checkPassword: [{validator: checkValidatePass, trigger: 'blur'}],
        verificationCode: [{Validator: checkValidateverificationCode, trigger: 'blur'}]
    })

    const submitForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                console.log('submit!')
                console.log(ruleForm)
                registerFunction(ruleForm.username, ruleForm.password, ruleForm.verificationCode)
                    .then(() => {
                        ElMessage({
                            showClose: true,
                            message: "正在自动登陆...",
                            type: 'success',
                        });
                        return loginFunction(ruleForm.username, ruleForm.password)
                    })
                    .then(function (result) {
                        loading.value = false;
                        router.push({name: 'home'})
                    })
            } else {
                console.log('error submit!')
                return false
            }
        })
    }

    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }
</script>
